<template>
  <div class="container">
    <div id="viewDiv"></div>
    <div id="legend"></div>
    <div id="zoom"></div>
    <!-- 加载状态提示（可选） -->
    <div class="loading-mask" v-if="loading">
      <el-spinner></el-spinner> 加载中...
    </div>
  </div>
</template>

<script>
import Map from "@arcgis/core/Map";
import MapView from "@arcgis/core/views/MapView";
import Zoom from "@arcgis/core/widgets/Zoom";
import Legend from "@arcgis/core/widgets/Legend";
import Swipe from "@arcgis/core/widgets/Swipe";
import WebTileLayer from "@arcgis/core/layers/WebTileLayer";
import GeoJSONLayer from "@arcgis/core/layers/GeoJSONLayer";
import MapImageLayer from "@arcgis/core/layers/MapImageLayer";
import Popup from "@arcgis/core/widgets/Popup";
import BasemapToggle from "@arcgis/core/widgets/BasemapToggle";
export default {
  data() {
    return {
      view: null,
      map: null,
      currentWmsLayer: null, // 保存当前图层引用
      imageryLayer: null,
      loading: false,
      swipe: null,
      rightLayer:null,
      leftLayer:null,
    };
  },
  mounted() {
    // 确保 DOM 渲染完成后初始化地图（避免容器尺寸问题）
    this.$nextTick(() => {
      this.initMap();
    });
  },
  beforeDestroy() {
    this.cleanupMapResources();
  },
  methods: {
    initMap() {
      const tile1 = new WebTileLayer({
        urlTemplate:
          "http://t1.tianditu.gov.cn/img_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=img&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=95e12b51a6d9a591822ef3a51d612352",
      });
      const tile2 = new WebTileLayer({
        urlTemplate:
          "http://t1.tianditu.gov.cn/cia_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=cia&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=95e12b51a6d9a591822ef3a51d612352",
      });
      const tile3 = new WebTileLayer({
        urlTemplate:
          "http://t1.tianditu.gov.cn/vec_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=vec&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=95e12b51a6d9a591822ef3a51d612352",
      });
      const tile4 = new WebTileLayer({
        urlTemplate:
          "http://t1.tianditu.gov.cn/cva_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=cva&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=95e12b51a6d9a591822ef3a51d612352",
      });
      this.map = new Map({
        basemap: {
          baseLayers: [tile3, tile4],
        },
      });
      const popup = new Popup({
        dockOptions: {
          buttonEnabled: false,
        },
        visibleElements: {
          featureNavigation: false,
          actionBar: false,
        },
      });
      this.view = new MapView({
        container: "viewDiv",
        map: this.map,
        constraints: {
          maxScale: 20000,
          rotationEnabled: false,
        },
        zoom: 7,
        center: [115, 27],
        popup: popup,
      });
      //全局事件总线
      this.$bus.$emit("arcgis-view-created", this.view);
      this.view.ui.components = []; // 移除默认的 UI 组件
      const zoom = new Zoom({
        view: this.view,
        container: "zoom",
      });
      this.view.ui.add(zoom);
      const legend = new Legend({
        view: this.view,
        container: "legend",
      });
      this.view.ui.add(legend, "bottom-left");
      const basemapToggle = new BasemapToggle({
        view: this.view,
        nextBasemap: {
          baseLayers: [tile1,tile2],
        },
      });
      this.view.ui.add(basemapToggle, "top-right");
    },
    //加载卷帘门
    addSwipe(left, right) {
      // 先移除旧图层
      // 移除现有影像图层
      if (this.imageryLayer) {
        this.map.remove(this.imageryLayer);
      }
      // 1. 先销毁已有的卷帘控件（避免重复添加）
      if (this.swipe) {
        this.view.ui.remove(this.swipe);
        this.swipe.destroy();
      }
      //先销毁现有图层
      if(this.leftLayer){
        this.map.remove(this.leftLayer)
      }
      if(this.rightLayer){
        this.map.remove(this.rightLayer)
      }
      //两个图层
       this.leftLayer = new MapImageLayer({
        url: `https://tjh.geosceneenterprise41.cn/server/rest/services/${left}/MapServer`,
      });
      // 先加载图层
      
      this.map.add(this.leftLayer);
      this.rightLayer = new MapImageLayer({
        url: `https://tjh.geosceneenterprise41.cn/server/rest/services/${right}/MapServer`,
      });
      // 先加载图层
      this.map.add(this.rightLayer);
      // 4. 等待两个图层的视图都准备好（关键：解决图层视图未创建的错误）
      Promise.all([
        this.view.whenLayerView(this.leftLayer),
        this.view.whenLayerView(this.rightLayer),
      ])
        .then(([leftLayerView, rightLayerView]) => {
          // 验证图层视图是否有效
          if (!leftLayerView || !rightLayerView) {
            throw new Error("图层视图创建失败");
          }

          // 5. 初始化卷帘控件
          this.swipe = new Swipe({
            view: this.view,
            leadingLayers: [this.leftLayer], // 左侧图层（使用正确创建的leftLayer）
            trailingLayers: [this.rightLayer], // 右侧图层（使用正确创建的rightLayer）
            direction: "horizontal", // 水平方向
            position: 50, // 初始位置（0-100，50为中间）
          });

          // 6. 添加到地图UI
          this.view.ui.add(this.swipe);
        })
        .catch((err) => {
          console.error("卷帘控件初始化失败:", err);
          this.$message.error("图层对比功能加载失败，请重试");
        });
    },
    toggleSwipe() {
      // 切换卷帘可见性（可选功能）
      if (this.swipe) {
        this.swipe.visible = !this.swipe.visible;
      }
      //先销毁现有图层
      if(this.leftLayer){
        this.map.remove(this.leftLayer)
      }
      if(this.rightLayer){
        this.map.remove(this.rightLayer)
      }
    },
    //加载年份npp
    addYearLayer(year) {
      // 移除现有影像图层
      if (this.imageryLayer) {
        this.map.remove(this.imageryLayer);
      }
      this.loading = true;
      // 创建影像图层
      this.imageryLayer = new MapImageLayer({
        url: `https://tjh.geosceneenterprise41.cn/server/rest/services/${year}/MapServer`,
      });
      // 先加载图层
      this.map.add(this.imageryLayer);
      this.loading = false;
    },
    //加载植被类型
    addLUCCLayer() {
      if (this.swipe) {
        this.view.ui.remove(this.swipe);
        this.swipe.destroy();
      }
      //先销毁现有图层
      if(this.leftLayer){
        this.map.remove(this.leftLayer)
      }
      if(this.rightLayer){
        this.map.remove(this.rightLayer)
      }
      // 先移除旧图层
      // 移除现有影像图层
      if (this.imageryLayer) {
        this.map.remove(this.imageryLayer);
      }
      // 创建影像图层
      this.imageryLayer = new MapImageLayer({
        url: `https://tjh.geosceneenterprise41.cn/server/rest/services/LUCC/MapServer`,
      });
      this.map.add(this.imageryLayer);
    },
    //加载Sen
    addSenLayer() {
      // 先移除旧图层
      // 移除现有影像图层
      if (this.imageryLayer) {
        this.map.remove(this.imageryLayer);
      }
      // 创建影像图层
      this.imageryLayer = new MapImageLayer({
        url: `https://tjh.geosceneenterprise41.cn/server/rest/services/sen_mk1/MapServer`,
      });
      // 先加载图层

      this.map.add(this.imageryLayer);
    },
    //加载Hurst
    addHurstLayer() {
      if (this.swipe) {
        this.view.ui.remove(this.swipe);
        this.swipe.destroy();
      }
      // 先移除旧图层
      // 移除现有影像图层
      if (this.imageryLayer) {
        this.map.remove(this.imageryLayer);
      }
      // 创建影像图层
      this.imageryLayer = new MapImageLayer({
        url: `https://tjh.geosceneenterprise41.cn/server/rest/services/HURST/MapServer`,
      });
      // 先加载图层

      this.map.add(this.imageryLayer);
    },
    //添加赣江矢量
    addGanJiangVec() {
      const ganjiang = new GeoJSONLayer({
        url: "static/geojson/npp/赣江.json",
        title: "赣江流域",
        outFields: ["*"], //属性
        renderer: {
          type: "simple",
          symbol: {
            type: "simple-fill",
            color: "rgba(150,150,150,0.2)",
            outline: {
              width: 0.7,
              color: [150, 150, 150],
            },
          },
        },
      });
      // 先加载图层
      this.map.layers.add(ganjiang);
    },
    /*************************
     * 资源清理（核心！防止内存泄漏）
     *************************/
    cleanupMapResources() {
      // 1. 销毁动态图层
      if (this.imageryLayer) {
        this.map.layers.remove(this.imageryLayer);
        this.imageryLayer = null;
      }
      if (this.leftLayer) {
        this.map.layers.remove(this.leftLayer);
        this.leftLayer = null;
      }
      if (this.rightLayer) {
        this.map.layers.remove(this.rightLayer);
        this.rightLayer = null;
      }
      if (this.swipe) {
        this.view.ui.remove(this.swipe);
        this.swipe.destroy();
        this.swipe = null
      }
      // 2. 销毁 MapView
      if (this.view) {
        this.view.destroy();
        this.view = null;
      }
      // 4. 清空 Map 引用
      this.map = null;
    },
  },
};
</script>

<style>
.container {
  position: relative;
  width: 100%;
  height: 100%;
}
#viewDiv {
  padding: 0;
  margin: 0;
  height: 100%;
  width: 100%;
}
/* 移除地图视图的边框 */
.esri-view {
  --esri-view-outline-color: unset !important;
  --esri-view-outline: unset !important;
  --esri-view-outline-offset: unset !important;
}
#legend {
  position: absolute;
  width: 180px;
  bottom: 5px;
  left: 205px;
  z-index: 100;
}
#zoom {
  position: absolute;
  top: 16px;
  right: 90px;
}
.loading-mask {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(255, 0, 0, 0.8);
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 16px;
}
</style>